import { mapActions, mapMutations, mapState } from 'vuex'
export default {
  data() {
    return {}
  },
  computed: {
    ...mapState('base', ['provinces', 'citys', 'countys'])
  },
  watch: {
    'formOption.data.provinceId'(parentId) {
      if (!parentId) {
        this.RESET_AREA_SELECT(['citys', 'countys'])
        this.loadAreaSelect()
        this.resetAreaValue(['cityId', 'areaId'])
      } else {
        this.getAreaConfig({ parentId, key: 'citys' })
      }
    },
    'formOption.data.cityId'(parentId) {
      if (!parentId) {
        this.RESET_AREA_SELECT(['countys'])
        this.loadAreaSelect()
        this.resetAreaValue(['cityId', 'areaId'])
      } else {
        this.getAreaConfig({ parentId, key: 'countys' })
      }
    }
  },
  created() {
    this.getAreaConfig()
  },
  methods: {
    ...mapActions('base', ['getAreaSelect']),
    ...mapMutations('base', ['RESET_AREA_SELECT']),
    // 重置选中的省市县
    resetAreaValue(keys) {
      keys.map(item => {
        for (const key in this.formOption.data) {
          if (item === key) {
            this.formOption.data[key] = ''
          }
        }
      })
    },
    // 筛选省市县数据
    filterArea(data) {
      const list = data.map(item => {
        return {
          label: item.areaName,
          value: item.id
        }
      })
      return list
    },
    // 加载选中的省市县
    loadAreaSelect() {
      this.formOption.items = this.formOption.items.map(item => {
        if (item.load) {
          if (item.value === 'provinceId') {
            item.selectList = this.filterArea(this.provinces)
          } else if (item.value === 'cityId') {
            item.selectList = this.filterArea(this.citys)
          } else {
            item.selectList = this.filterArea(this.countys)
          }
        }
        return item
      })
    },
    // 加载省市县的slectList
    getAreaConfig(data = { parentId: 100000, key: 'provinces' }) {
      this.getAreaSelect(data).then(() => {
        this.loadAreaSelect()
      })
    }
  }
}
